import { useState } from "react";

function TodoList() {
  const [todos, setTodos] = useState(["task1", "task2", "task3"]);
  const [newTask, setnewTask] = useState("");
  function addTask() {
    if (newTask !== "") {
      setTodos([...todos, newTask]);
      setnewTask("");
    }
  }
  function deletedTask(index) {
    setTodos(todos.filter((todo, i) => i !== index));
  }
  function moveUp(index) {
    // 将点击的元素与前一位元素交换位置
    setTodos((prevTodos) => {
      // 边界条件检查
      if (index <= 0 || index >= prevTodos.length) {
        return [...prevTodos]; // 如果索引无效，直接返回原数组
      }

      // 创建新数组并交换元素
      const newTodos = [...prevTodos];
      [newTodos[index - 1], newTodos[index]] = [newTodos[index], newTodos[index - 1]];

      return newTodos;
    });
  }
  function moveDown(index) {
    // 将点击的元素与后一位元素交换位置
    setTodos((prevTodos) => {
      // 边界条件检查
      if (index + 1 == prevTodos.length) {
        return [...prevTodos]; // 如果索引无效，直接返回原数组
      }

      // 创建新数组并交换元素
      const newTodos = [...prevTodos];
      [newTodos[index], newTodos[index + 1]] = [newTodos[index + 1], newTodos[index]];

      return newTodos;
    });
  }
  return (
    <div>
      <p>task列表</p>
      <div className="addmodule">
        <input type="text" value={newTask} onChange={(e) => setnewTask(e.target.value)} />
        <button className="addbtn" onClick={addTask}>
          添加
        </button>
      </div>
      <ol>
        {todos.map((todo, index) => (
          <li key={index}>
            <p>{todo}</p>
            <button className="deletebtn" onClick={() => deletedTask(index)}>
              删除
            </button>
            <button onClick={() => moveUp(index)}>上移</button>
            <button onClick={() => moveDown(index)}>下移</button>
          </li>
        ))}
      </ol>
    </div>
  );
}
export default TodoList;
